<template>
  <div class="container">
    <!-- 状态栏 -->
    <div class="status-bar">
      <span class="time">9:41</span>
      <span class="title">聊天</span>
    </div>

    <!-- 聊天内容 -->
    <div class="chat-content" ref="chatContentRef">
      <div class="time-divider">{{ formatDate(new Date()) }}</div>

      <!-- 消息列表 -->
      <template v-for="(msg, index) in messages" :key="index">
        <!-- 时间分割线，当消息间隔超过5分钟显示 -->
        <div v-if="shouldShowTimeDivider(index)" class="time-divider">
          {{ formatTime(msg.timestamp) }}
        </div>

        <!-- 对方消息 -->
        <div v-if="msg.senderId !== currentUserId" class="message left">
          <img
            class="avatar"
            :src="'https://dummyimage.com/40x40/FFA500/fff'"
            style="width:40px;height:40px;border-radius:50%;"
          />
          <div class="bubble">
            <div class="text">{{ msg.content }}</div>
          </div>
        </div>

        <!-- 己方消息 -->
        <div v-else class="message right">
          <div class="bubble own">
            <div class="text">{{ msg.content }}</div>
          </div>
          <img
            class="avatar"
            :src="'https://dummyimage.com/40x40/FF0000/fff'"
            style="width:40px;height:40px;border-radius:50%;"
          />
        </div>
      </template>
    </div>

    <!-- 输入工具栏 -->
    <div class="input-toolbar">
      <van-icon name="audio" size="20" class="icon" />
      <van-field
        v-model="inputContent"
        class="input-field"
        placeholder="输入消息"
        borderless
      />
      <van-icon name="smile-o" size="20" class="icon" />
      <van-button size="small" type="primary" class="send-btn" @click="sendMessage">发送</van-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import type { Message } from '../services/chatService'
import { useCounterStore } from '@/stores/counter';

import { 
  getChatHistory, 
  sendPrivateMessage,
  markMessagesAsRead,
  startSignalRConnection,
  setupMessageHandlers
} from '../services/chatService'

// 路由参数
const route = useRoute();
const router = useRouter();
const receiverId = computed(() => route.params.receiverId as string);

const store = useCounterStore();

// 当前用户ID（应该从用户状态或本地存储获取）
const currentUserId = ref<string>(store.useStore.mId || '');

// 消息列表
const messages = ref<Message[]>([]);
const inputContent = ref<string>('');
const chatContentRef = ref<HTMLElement | null>(null);

// 发送消息
const sendMessage = async () => {
  if (!inputContent.value.trim() || !currentUserId.value || !receiverId.value) return;
  
  try {
    await sendPrivateMessage(receiverId.value, inputContent.value);
    
    // 添加到本地消息列表
    messages.value.push({
      id: Date.now().toString(),
      content: inputContent.value,
      senderId: currentUserId.value,
      receiverId: receiverId.value,
      timestamp: Date.now(),
      status: 'sent'
    });
    
    inputContent.value = '';
    scrollToBottom();
  } catch (error) {
    console.error('发送消息失败:', error);
    showToast('发送消息失败，请重试');
  }
};

// 加载历史消息
const loadHistoryMessages = async () => {
  if (!currentUserId.value || !receiverId.value) return;
  
  try {
    const history = await getChatHistory(currentUserId.value, receiverId.value);
    messages.value = history;
    
    // 标记消息为已读
    const unreadMessages = history
      .filter(msg => msg.senderId === receiverId.value && msg.status !== 'read')
      .map(msg => msg.id);
      
    if (unreadMessages.length > 0) {
      await markMessagesAsRead(unreadMessages);
    }
    
    scrollToBottom();
  } catch (error) {
    console.error('加载聊天历史失败:', error);
    showToast('加载聊天历史失败，请重试');
  }
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContentRef.value) {
      chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight;
    }
  });
};

// 格式化日期
const formatDate = (date: Date) => {
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
};

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 判断是否显示时间分割线
const shouldShowTimeDivider = (index: number) => {
  if (index === 0) return true;
  
  const currentMsg = messages.value[index];
  const prevMsg = messages.value[index - 1];
  
  // 如果两条消息间隔超过5分钟，显示时间分割线
  return currentMsg.timestamp - prevMsg.timestamp > 5 * 60 * 1000;
};

// 组件挂载时建立连接并加载历史消息
onMounted(async () => {
  if (!currentUserId.value) {
    router.push('/login');
    return;
  }
  
  try {
    // 建立SignalR连接
    await startSignalRConnection();
    
    // 设置消息处理器
    setupMessageHandlers(
      currentUserId.value,
      (message) => {
        // 只处理来自当前聊天对象的消息
        if (message.senderId === receiverId.value) {
          messages.value.push(message);
          // 标记消息为已读
          markMessagesAsRead([message.id]).catch(error => {
            console.error('标记消息已读失败:', error);
          });
          scrollToBottom();
        }
      },
      () => {
        // 连接成功后加载历史消息
        loadHistoryMessages();
      },
      (error) => {
        console.error('SignalR连接错误:', error);
        showToast('聊天连接出错，请重试');
      }
    );
  } catch (error) {
    console.error('初始化聊天失败:', error);
    showToast('初始化聊天失败，请重试');
  }
});

// 组件卸载时断开连接
onUnmounted(() => {
  // 连接会在chatService中统一管理，不需要在这里关闭
});
</script>
<style scoped>
.container {
  height: 100vh;
  background: #F0F0F0;
}

.status-bar {
  padding: 10px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.chat-content {
  padding: 10px;
  height: calc(100vh - 120px);
  overflow-y: auto;
}

.time-divider {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin: 15px 0;
}

.message {
  display: flex;
  margin: 15px 0;
  gap: 10px;
}

.left {
  justify-content: flex-start;
}

.right {
  justify-content: flex-end;
}

.bubble {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 15px;
  background: white;
  position: relative;
}

.bubble.own {
  background: #95EC69;
}

.input-toolbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px;
  background: white;
  display: flex;
  align-items: center;
  gap: 10px;
  border-top: 1px solid #eee;
}

.input-field {
  flex: 1;
  background: #F5F5F5;
  border-radius: 20px;
  padding: 8px 15px;
}

.send-btn {
  border-radius: 15px;
  padding: 8px 20px;
}

.icon {
  color: #666;
}
</style>